<template>
	<view>
		<u-upload 
			:fileList="fileList" 
			@afterRead="afterRead" 
			@delete="deletePic" 
			:multiple="multiple"
			:maxCount="limit"
			:deletable="deletable"
			:previewFullImage="previewFullImage"
			:accept="accept"
			:disabled="disabled || !writable"
		></u-upload>
		<view v-show="required && validator" class="requiredMessage">{{ requiredMessage }}</view>
	</view>
</template>

<script>
import { getToken } from '../utils'
export default {
	data() {
		return {
			validator: false,
			fileList: [],
			submitData: []
		};
	},
	props: {
		value: {
			type: Array,
			default: () => []
		},
		required: {
			type: Boolean,
			default: false
		},
		requiredMessage: {
			type: String,
			default: '值不能为空'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		writable: {
			type: Boolean,
			default: true
		},
		limit: {
			type: Number,
			default: 3
		},
		action: {
			type: String,
			default: '/api/sys/file/webupload/upload?uploadPath=/formbuilder'
		},
		multiple: {
			type: Boolean,
			default: true
		},
		deletable: {
			type: Boolean,
			default: true
		},
		previewFullImage: {
			type: Boolean,
			default: true
		},
		// 接受的文件类型，file只支持H5（只有微信小程序才支持把accept配置为all、media）
		accept: {
			type: String,
			default: 'image'
		},
		serverUrl: {
			type: String,
			default: 'http://192.168.67.47:8080/xps-vue'
		},
		tokenKey: {
			type: String,
			default: 'token'
		}
	},
	computed: {
		validateStatus() {
			return this.$store?.state?.validate?.status || false
		}
	},
	watch: {
		value: {
			handler() {
				this.submitData = []
				this.fileList = []
				// 回显操作
				if(this.value.length) {
					this.value.forEach(item => {
						this.fileList.push({
							status: 'success', 
							message: '',
							url: item.url ? this.serverUrl + item.url : this.serverUrl + item
						})
						this.submitData.push(...this.value)
					})
				}
			},
			immediate: true,
			// deep: true
		},
		validateStatus() {
			if(this.validateStatus && this.required) {
				if(!this.val) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		},
		fileList() {
			if(this.validateStatus && this.required) {
				if(!this.fileList.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		}
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this.fileList.splice(event.index, 1)
			this.submitData.splice(event.index, 1)
			// 移除 
			this.$emit('input', this.submitData)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			// let fileListLen = this.fileList.length
			lists.forEach(item => {
				this.fileList.push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				let result
				try {
					result = await this.uploadFilePromise(lists[i].url)
				} catch(e) {console.error("[Error upload]:", e)}
				// let item = this.fileList[fileListLen]
				// this.fileList.splice(fileListLen, 1, Object.assign(item, {
				// 	status: 'success',
				// 	message: '',
				// 	url: this.serverUrl + result.url
				// }))
				if(result) {
					this.submitData.push({
						id: result.id,
						url: result.url,
						status: 'success',
						percent: 100,
						key: new Date().getTime() + '_' + Math.ceil(Math.random() * 99999)
					})
				}
				// fileListLen++
			}
			// 上传成功
			this.$emit('input', this.submitData)
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.serverUrl + this.action,
					filePath: url,
					name: 'file',
					header: {
						[this.tokenKey]: getToken(this.tokenKey)
					},
					success: res => {
						let rd = JSON.parse(res.data)
						resolve(rd)
					},
					fail: err => {
						reject(err)
					}
				})
			})
		}
	}
}
</script>

<style scoped>
.requiredMessage {
	width: 100%;
	height: 50rpx;
	line-height: 50rpx;
	color: #f56c6c;
	font-size: 22rpx;
}
</style>